package arkham.gui;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;

import javax.swing.JList;
import javax.swing.JTextArea;
import javax.swing.ListCellRenderer;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class MultilineListCellRenderer extends JTextArea implements ListCellRenderer
{
    private static final long serialVersionUID = -5235344952141143239L;
    private static UIDefaults defaults = UIManager.getLookAndFeelDefaults();;
    private final int width;

    public MultilineListCellRenderer(int w)
    {
        super();
        this.width = w;
        setEditable(false);
        setCursor(null);
        setOpaque(true);
        setFocusable(false);
        setLineWrap(true);
        getDocument().addDocumentListener(new DocumentListener(){
            @Override
            public void changedUpdate(DocumentEvent e)
            {
                // Resize the component when the text changes, but maintain the width

                FontMetrics fm = getFontMetrics(getFont());
                int lines = (fm.stringWidth(getText()) / width) + 1;
                setPreferredSize(new Dimension(width, fm.getHeight() * lines));
            }

            @Override
            public void insertUpdate(DocumentEvent e)
            {
                changedUpdate(e);
            }

            @Override
            public void removeUpdate(DocumentEvent e)
            {
                changedUpdate(e);
            }

        });
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus)
    {
        this.setMaximumSize(new Dimension(list.getWidth(), Integer.MAX_VALUE));
        if (isSelected || cellHasFocus)
        {
            this.setBackground(defaults.getColor("TextArea.selectionBackground"));
            this.setForeground(defaults.getColor("TextArea.selectionForeground"));
        }
        else
        {
            this.setBackground(defaults.getColor("TextArea.background"));
            this.setForeground(defaults.getColor("TextArea.foreground"));
        }
        revalidate();
        return this;
    }

}
